package com.tarena.lbs.coupon.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.coupon.dao.repository.CouponRepository;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import com.tarena.lbs.coupon.pojo.query.CouponQuery;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;

@Slf4j
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponRepository couponRepository;

    @Override
    public Integer createCoupon(CouponParam param) throws BusinessException {
        // 参数校验已通过JSR-303注解完成

        try {
            // 构建优惠券PO对象
            CouponPO couponPO = new CouponPO();
            BeanUtils.copyProperties(param, couponPO);

            // 处理日期格式转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            couponPO.setStartDate(sdf.parse(param.getStartDate()));
            couponPO.setEndDate(sdf.parse(param.getEndDate()));

            // 设置默认值
            couponPO.setCreateAt(new Date());
            couponPO.setUpdateAt(new Date());
            // 修复：优惠券创建时应该设为未开始状态(1)，而不是已结束状态(3)
            couponPO.setStatus(2);// 1:未开始 2:进行中 3:已结束
            couponPO.setUsageNum(0);
            couponPO.setEnableStatus(1); // 0:禁用 1: 启用
            couponPO.setCouponStatus(1);

            // 关键点：设置商家ID（需要根据实际系统上下文获取）
            // 这里假设从当前登录用户或会话中获取商家ID
            Integer businessId = 1; // 示例值，需要替换为实际获取方式
            couponPO.setBusinessId(businessId);

            // 保存优惠券
            return couponRepository.save(couponPO);
        } catch (ParseException e) {
            log.error("日期格式转换错误", e);
            throw new BusinessException("COUPON_DATE_ERROR", "日期格式错误");
        } catch (Exception e) {
            log.error("创建优惠券失败", e);
            throw new BusinessException("COUPON_CREATE_FAIL", "创建优惠券失败");
        }
    }

    @Override
    public CouponVO getCouponDetail(Integer Id) throws BusinessException {
        if (Id == null) {
            throw new BusinessException("COUPON_ID_EMPTY", "优惠券ID不能为空");
        }
        
        CouponPO couponPO = couponRepository.getById(Id);
        if (couponPO == null) {
            throw new BusinessException("COUPON_NOT_EXIST", "优惠券不存在");
        }

        return convertToVO(couponPO);
    }

    @Override
    public PageResult<CouponVO> pageList(CouponQuery query) {
        // 分页查询优惠券列表
        PageInfo<CouponPO> pageInfo = couponRepository.pageList(query);
        
        // 转换为VO对象
        List<CouponVO> voList = null;
        if (pageInfo.getList() != null && !pageInfo.getList().isEmpty()) {
            voList = pageInfo.getList().stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
        }
        
        // 构建分页结果
        PageResult<CouponVO> pageResult = new PageResult<>();
        pageResult.setObjects(voList);
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        
        return pageResult;
    }

    @Override
    public void deleteCouponId(Integer id) throws BusinessException {
        log.info("删除优惠券，ID: {}", id);
        if (id == null) {
            throw new BusinessException("COUPON_ID_EMPTY", "ID不能为空");
        }
        
        // 检查优惠券是否存在
        CouponPO couponPO = couponRepository.getById(id);
        if (couponPO == null) {
            throw new BusinessException("COUPON_NOT_EXIST", "优惠券不存在");
        }
        
        // 假删除：将coupon_status设置为0
        couponRepository.updateStatus(id, 0);
    }

    @Override
    public void receiveCoupon(Integer userId, Integer couponId) {

    }

    private CouponVO convertToVO(CouponPO po) {
        CouponVO vo = new CouponVO();
        BeanUtils.copyProperties(po, vo);

        // 填充状态描述
        if (po.getStatus() != null) {
            switch (po.getStatus()) {
                case 1:
                    vo.setStatusDesc("未开始");
                    break;
                case 2:
                    vo.setStatusDesc("进行中");
                    break;
                case 3:
                    vo.setStatusDesc("已结束");
                    break;
                default:
                    vo.setStatusDesc("未知状态");
            }
        }

        // 填充优惠券类型描述
        if (po.getCouponType() != null) {
            switch (po.getCouponType()) {
                case 1:
                    vo.setCouponTypeDesc("满减券");
                    break;
                case 2:
                    vo.setCouponTypeDesc("折扣券");
                    break;
                case 3:
                    vo.setCouponTypeDesc("现金券");
                    break;
                case 4:
                    vo.setCouponTypeDesc("免运费券");
                    break;
                case 5:
                    vo.setCouponTypeDesc("特价券");
                    break;
                default:
                    vo.setCouponTypeDesc("未知类型");
            }
        }

        // 填充启用状态描述
        if (po.getEnableStatus() != null) {
            if (po.getEnableStatus() == 0) {
                vo.setEnableStatusDesc("禁用");
            } else if (po.getEnableStatus() == 1) {
                vo.setEnableStatusDesc("启用");
            } else {
                vo.setEnableStatusDesc("未知状态");
            }
        }
        
        return vo;
    }

    @Override
    public void updateCouponEnableStatus(Integer id, Integer enableStatus) throws BusinessException {
        log.info("更新优惠券启用状态，ID: {}, 启用状态: {}", id, enableStatus);
        try {
            // 参数校验
            if (id == null) {
                throw new BusinessException("COUPON_ID_EMPTY", "优惠券ID不能为空");
            }
            if (enableStatus == null || (enableStatus != 0 && enableStatus != 1)) {
                throw new BusinessException("COUPON_STATUS_INVALID", "状态值必须为0或1");
            }
            
            // 检查优惠券是否存在
            CouponPO couponPO = couponRepository.getById(id);
            if (couponPO == null) {
                throw new BusinessException("COUPON_NOT_EXIST", "优惠券不存在");
            }
            
            // 更新优惠券状态
            couponRepository.updateEnableStatus(id, enableStatus);
            log.info("更新优惠券状态成功，ID: {}", id);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新优惠券状态失败，ID: {}", id, e);
            throw new BusinessException("COUPON_UPDATE_STATUS_FAIL", "更新优惠券状态失败，请稍后重试");
        }
    }
}